package com.plentitude.easytrader.ui;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.Map;

import org.apache.http.HttpVersion;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import com.plentitude.easytrader.R;
import com.plentitude.easytrader.util.LruCacheLinkedHashMap;
import android.app.Application;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;


/**
 * This class contains constants, images cache and methods, shared via all activities.
 * 
 * @author team@getstarted.com.ua
 */
public class ETApplication extends Application {
    public static boolean USE_SD = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	public static String CACHE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.easytrader/";
	private static ETApplication instance; 
	private static Map<Object, SoftReference<Drawable>> drawableHashMap;
	private final String TAG = "ETApplication";
	private SecurityManager securityManager;
	private String username;
	private String password;
	private Boolean isOnline;
	private ThreadSafeClientConnManager cm;
	private HttpParams httpParams;
	
	
	public static ETApplication getInstance() {
		return instance;
	}

    /**
     * Create an HttpClient with the ThreadSafeClientConnManager.
     * This connection manager must be used if more than one thread will
     * be using the HttpClient.
     */
	public ThreadSafeClientConnManager getConnectionManager() {
        if(cm == null) {
	        SchemeRegistry registry = new SchemeRegistry();
	        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
	        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	        registry.register(new Scheme("https", sslSocketFactory, 443));
			cm = new ThreadSafeClientConnManager(getHttpParams(), registry);
        }
        return cm;
	}

    /**
     * Create an HttpParams instance.
     */
	public HttpParams getHttpParams() {
        if(httpParams == null) {
	        httpParams = new BasicHttpParams();
	        httpParams.setBooleanParameter("http.protocol.expect-continue", false);
	        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
	        HttpConnectionParams.setSoTimeout(httpParams, 5000);
	        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
	        HttpProtocolParams.setContentCharset(httpParams, "utf-8");
        }
        return httpParams;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		instance = this;
		drawableHashMap = Collections.synchronizedMap(new LruCacheLinkedHashMap(50));
	}
	
	public Map<Object, SoftReference<Drawable>> getDrawableHashMap() {
		return drawableHashMap;
	}
	
	public Drawable getArrowUpDrawable() {
		SoftReference<Drawable> icArrowUp = getDrawableHashMap().get("icArrowUp");
		if(icArrowUp == null) {
			Drawable drawable = getResources().getDrawable(R.drawable.ic_arrow_up);
			icArrowUp = new SoftReference<Drawable>(drawable);   
			getDrawableHashMap().put("icArrowUp", icArrowUp);   
		}
		return icArrowUp.get();
	}

	public Drawable getArrowDownDrawable() {
		SoftReference<Drawable> icArrowDown = getDrawableHashMap().get("icArrowDown");
		if(icArrowDown == null) {
			Drawable drawable = getResources().getDrawable(R.drawable.ic_arrow_down);
			icArrowDown = new SoftReference<Drawable>(drawable);   
			getDrawableHashMap().put("icArrowDown", icArrowDown);   
		}
		return icArrowDown.get();
	}

	public Drawable getCloseDrawable() {
		SoftReference<Drawable> icClose = getDrawableHashMap().get("icClose");
		if(icClose == null) {
			Drawable drawable = getResources().getDrawable(R.drawable.ic_menu_close);
			icClose = new SoftReference<Drawable>(drawable);   
			getDrawableHashMap().put("icClose", icClose);   
		}
		return icClose.get();
	}
	
	public boolean isOnline(boolean force) {
		if(isOnline == null || force) {
			try {
				final ConnectivityManager conMgr = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
				final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
				if(activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
				    isOnline = true;
				} else {
				    isOnline = false;
				} 
			} catch(Exception e) {
				Log.e(TAG, e.toString());
				isOnline = false;
			}
		}
		return isOnline;
	}
    
    /** Instantiate SecurityManager */
    public SecurityManager getSecurityManager() {
    	if(securityManager == null) {
    		securityManager = new SecurityManager();
    	}
    	return securityManager;
    }
    
    public void setUsername(String username) {
    	this.username = username;
    }
    
    public String getUsername() {
    	return username;
    }
    
    public void setPassword(String password) {
    	this.password = password;
    }
    
    public String getPassword() {
    	return password;
    }

}

